package com.ruoyi.common.utils;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

public class CdnUtil {

    private static String CDN_PRIVATE_KEY = "kkccdn@1a2b3c";

    public static String getCdnAuthUrl(String url, Date expiration) {

        try {
            URL netUrl = new URL(url);
            String key = netUrl.getPath();
            String rand = UUID.randomUUID().toString().replace("-", "");
            int time = (int) (expiration.getTime() / 1000);
            String base = String.format("%s-%s-%s-0-%s", key, time, rand, CDN_PRIVATE_KEY);
            String hashValue = Md5Utils.md5(base.getBytes());
            String authKey = String.format("%s-%s-0-%s", time, rand, hashValue);
            return url + "?auth_key=" + authKey;
        } catch (MalformedURLException e) {
        }
        return url;

    }

    /**
     * @param url
     * @param resourceName
     * @return
     */
    public static String appendFileName(String url, String resourceName) {
        if (StringUtils.isEmpty(url)) {
            return url;
        }
        if (url.indexOf("?") > 0) {
            url = url + "&filename=/" + resourceName;
        } else {
            url = url + "?filename=/" + resourceName;
        }
        return url;
    }

    public static void main(String[] args) {
        String url = "http://resource.kkc.cdn.youzhi.net/kkpoem/poemwyw_cizu/1/poemwyw_cizu";
        System.out.println(getCdnAuthUrl(url, DateUtils.addMinutes(new Date(), 30)));
    }

}
